<template>
  <view class="bg common">
    <u-toast ref="uToast"></u-toast>
    <!--提示-->
    <view class="alert">
      <view>
        <u-image
            :src="showImage(this.bannerImage)"
            mode="widthFix"
            width="88vw"
            height="auto"
            :show-loading="true"
        >
          <u-skeleton
              slot="loading"
              rows="0"
              :title="true"
              title-width="88vw"
              title-height="30vh"
          ></u-skeleton>
        </u-image>
      </view>
      <!--提示文字-->
      <view class="text">
        <u-alert
            title="借书或者还书请点击下方按钮扫码"
            description="一定要扫描图书角的书后的条形码，条形码位置如上图所示，切记不要尝试去扫描一些奇怪的东西，否则后果自负"
            type="primary"
            :show-icon="true"
        >

        </u-alert>
      </view>
    </view>
    <!--弹出层-->
    <u-popup
        :show="popupStatus"
        mode="center"
        :round="10"
        :closeable="btnStatus"
        overlay-opacity="0.1"
        :safe-area-inset-bottom="false"
        :custom-style="{
          padding:'15px',
          boxShadow: '0 3px 10px 0px rgba(0, 0, 0, 0.1)'
        }"
        @close="closePopup">
      <u-toast ref="popupToast"></u-toast>
      <u-skeleton
          :title="true"
          title-height="30vh"
          title-width="21.1vh"
          rows-width="80vw"
          rows="5"
          :loading="loadingStatus"
      >
        <!--确认信息-->
        <view class="confirm">
          <!--图书信息-->
          <view class="book" v-if="bookStatus">
            <!--图片-->
            <view class="img">
              <u-image
                  :src="bookInfo.cover"
                  height="30vh"
                  width="21.1vh"
                  mode="heightFix"
              ></u-image>
            </view>
            <!--书名-->
            <view class="name">
              <u-text
                  :text="bookInfo.name"
              ></u-text>
            </view>
          </view>
          <view class="book" v-else>
            <u-empty
                mode="data"
                text="找不到书的信息"
            >
            </u-empty>
          </view>
          <!--借阅信息-->
          <!--没人借-->
          <view class="borrow" v-if="bookStatus&&!isSelfBorrow">
            <!--文字信息-->
            <view class="text">
              <u-alert
                  :title="!bookInfo.status?backInfo.text:borrowInfo.text"
                  :description="!bookInfo.status?backInfo.description:borrowInfo.description"
                  :type="!bookInfo.status?'warning':'primary'"
                  :center="true"
              ></u-alert>
            </view>
            <!--借阅时长-->
            <view class="select" v-if="bookInfo.status">
              <u-cell
                  title="借阅时长"
                  icon="clock"
                  :border="false"
              >
                <view slot="value" class="select-time">
                  <u-number-box
                      v-model="borrowInfo.time"
                      :min="1"
                      :max="4"
                      integer
                      :disabled-input="true"
                  ></u-number-box>
                  <u-text
                      text="周"
                      type="info"
                      :custom-style="{
                        marginLeft:'10px'
                    }"
                  ></u-text>
                </view>
              </u-cell>
            </view>
          </view>
          <!--自己借的-->
          <view class="borrow" v-else-if="isSelfBorrow&&bookStatus">
            <!--文字信息-->
            <view class="text">
              <u-alert
                  :title="selfBorrowInfo.text"
                  :description="selfBorrowInfo.borrowDesc"
                  type="warning"
                  :center="true"
              ></u-alert>
            </view>
          </view>
          <!--别人借的-->
          <view class="borrow" v-else>
            <!--文字信息-->
            <view class="text">
              <u-alert
                  title="图书角没有这本书"
                  description="请不要扫一些奇怪的东西"
                  type="error"
                  :center="true"
              ></u-alert>
            </view>
          </view>
          <!--按钮-->
          <view class="btn">
            <!--取消-->
            <view class="btn-item">
              <u-button
                  text="取消"
                  shape="circle"
                  plain
                  type="primary"
                  :loading="!btnStatus"
                  :disabled="!btnStatus"
                  @click="closePopup"
              ></u-button>
            </view>
            <!--确定-->
            <view class="btn-item">
              <!--重扫 没书或者书被其他人借了-->
              <u-button
                  v-if="!bookStatus||(isBorrow&&!isSelfBorrow)"
                  text="重扫"
                  shape="circle"
                  type="primary"
                  @click="scanISBN"
              ></u-button>
              <!--还书 书被我借了-->
              <u-button
                  v-else-if="isBorrow&&isSelfBorrow"
                  text="归还"
                  shape="circle"
                  type="primary"
                  :loading="!btnStatus"
                  :disabled="!btnStatus"
                  @click="backBook"
              ></u-button>
              <!--借书-->
              <u-button
                  v-else
                  text="借阅"
                  shape="circle"
                  type="primary"
                  :loading="!btnStatus"
                  :disabled="!btnStatus"
                  @click="borrowBook"
              ></u-button>
            </view>
          </view>
        </view>
      </u-skeleton>
    </u-popup>
    <!--按钮-->
    <view class="buttons">
      <u-button
          text="扫描条形码"
          shape="circle"
          ripple="ripple"
          type="primary"
          size="large"
          @click="scanISBN"
      ></u-button>
    </view>
  </view>
</template>

<script>
import {getStorageImage} from '@/common/image/imageUtil'

export default {
  data() {
    return {
      bannerImage: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-9323a98f-5eb6-4a33-bdfc-2c8f27b6f817/270e1f89-e5cc-46aa-a1ef-ca5aaf8a48fa.png',
      bookInfo: {},
      recordInfo: {},
      userInfo: {},
      backInfo: {
        text: '哎呀哈，这本书被借走了',
        description: '换本书读吧，咱还有的选'
      },
      borrowInfo: {
        text: '您即将借阅这本书',
        description: '多了解了解，多接触接触，多学习学习',
        time: 1
      },
      selfBorrowInfo: {
        text: '您即将还这本书',
        borrowDesc: '好借好还，再借不难'
      },
      //是否有这本书
      bookStatus: false,
      //是否正在加载
      loadingStatus: false,
      //是否显示弹出层
      popupStatus: false,
      //按钮是否可点击
      btnStatus: true
    }
  },
  methods: {
    //显示图片
    showImage(url) {
      return getStorageImage(this.bannerImage)
    },
    //扫描条码
    scanISBN() {
      //清空历史数据
      this.recordInfo = {}
      this.bookInfo = {}
      this.bookStatus = false
      let _this = this
      uni.scanCode({
        scanType: 'qrCode',
        success: (res) => {
          _this.getBookInfo(res.result)
        },
        fail: (err) => {
          _this.$refs.uToast.show({
            message: err.errMsg || '扫描失败',
            type: 'error'
          })
        }
      })
    },
    //获取图书信息
    async getBookInfo(isbn) {
      this.popupStatus = true
      this.loadingStatus = true
      try {
        //查数据库
        const db = uniCloud.database()
        const recordTemp = db.collection('record')
            .where('status == "borrow"')
            .getTemp()
        const bookTemp = db.collection('book')
            .where({
              isbn: isbn
            })
            .getTemp()
        const book = (await db.collection(bookTemp, recordTemp)
            .get()).result.data
        //检查是否有书
        if (book.length === 0) {
          //没书
          this.bookStatus = false
        } else {
          //有书
          this.bookStatus = true
          this.bookInfo = book[0]
          //检查是否有借还记录
          if (book[0]._id.record.length > 0) {
            //有记录
            this.recordInfo = book[0]._id.record[0]
          }
          this.bookInfo._id = book[0]._id._value
        }
      } catch (e) {
        this.$refs.uToast.show({
          message: e || '获取图书信息失败',
          type: 'error'
        })
      }
      this.loadingStatus = false
    },
    //借书
    async borrowBook() {
      this.btnStatus = false
      try {
        await uni.requestSubscribeMessage({
          tmplIds: ['sVW1LT6sDt33czuxqq4qq0tUslwhwYPUgVN5wjYeod4', 'g4RMcRLwZxfvdtUFuxmGVis46XZAaeualEv6-vRAQEs', 'SqlXSDlBiaYv4KDDtz3BNPfb0-X_mNYDt_sV1OzhiZg'],
          success(res) {
            console.log(res)
          }
        })
        const db = uniCloud.database()
        //生成借阅数据
        let recordItem = {
          'bookId': this.bookInfo._id,
          'userId': this.userInfo._id,
          'borrowTime': Number(this.borrowInfo.time * 7),
          'description': '',
          'status': 'borrow'
        }
        const recordRes = (await db.collection('record').add(recordItem)).result
        let recordActionItem = {
          'date': new Date().getTime(),
          'userId': this.userInfo._id,
          'recordId': recordRes.id,
          'status': 'borrow'
        }
        //添加表单动作
        const recordActionQuery = db.collection('record_action').add(recordActionItem)
        //更新书的状态
        const bookUpdateQuery = db.collection('book').doc(this.bookInfo._id).update({status: false})
        //聚合发送请求
        try {
          await db.multiSend(recordActionQuery, bookUpdateQuery).then(res => {
            console.log(res)
          })
        } catch (e) {
          console.log(e)
        } finally {
          this.closePopup()
          this.$refs.uToast.show({
            message: '借阅成功，记得按时还哦',
            type: 'success'
          })
        }

      } catch (e) {
        console.log(e)
        this.$refs.popupToast.show({
          message: String(e) || '借书失败',
          type: 'error'
        })
      } finally {
        this.btnStatus = true
      }
    },
    //还书
    async backBook() {
      this.btnStatus = false
      try {
        const db = uniCloud.database()
        //更新record状态
        const recordUpdateQuery = db.collection('record')
            .doc(this.recordInfo._id)
            .update({
              status: 'backing'
            })
        let recordActionItem = {
          'date': new Date().getTime(),
          'userId': this.userInfo._id,
          'recordId': this.recordInfo._id,
          'status': 'backing'
        }
        //添加record_action
        await db.collection('record_action').add(recordActionItem)
        // 查询用户名
        let user = (await db.collection('user').doc(this.userInfo._id).field('name').get()).result.data[0]
        // 查询用户归还图书名
        let book = (await db.collection('book').doc(this.bookInfo._id).field('name').get()).result.data[0]
        uniCloud.callFunction({name: 'notice', data: {user, book}}).catch(console.log)
        this.$refs.uToast.show({
          message: '申请归还成功，等待管理员确认',
          type: 'success'
        })
        this.closePopup()
      } catch (e) {
        console.log(e)
        this.$refs.popupToast.show({
          message: String(e) || '还书失败',
          type: 'error'
        })
      } finally {
        this.btnStatus = true
      }
    },
    //读取用户信息
    getUserInfo() {
      if (uni.getStorageSync('userInfo')) {
        this.userInfo = uni.getStorageSync('userInfo')
      }
    },
    //关闭弹出层
    closePopup() {
      this.popupStatus = false
    }
  },
  computed: {
    //是不是我借的
    isSelfBorrow() {
      return this.recordInfo.userId === this.userInfo._id
    },
    //是否被借
    isBorrow() {
      return !this.bookInfo.status
    }
  },
  onLoad() {
    this.getUserInfo()
  }
}
</script>

<style lang="scss">
.bg {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;

  .alert {
    margin-top: 5vh;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .text {
      margin-top: 5vh;
      width: 100%;
    }
  }

  .buttons {
    width: 100%;
    margin-bottom: 15vh;
  }

  .confirm {
    width: 80vw;

    .book {
      margin: 5vh 0 3vh 0;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .img {
        display: flex;
        justify-content: center;
      }

      .name {
        margin-top: 2vh;
      }
    }

    .borrow {
      .text {

      }

      .select {
        margin-top: 2vh;

        .select-time {
          display: flex;
        }
      }
    }

    .btn {
      margin-top: 2vh;
      display: flex;
      justify-content: space-around;

      .btn-item {
        width: 40%;
      }
    }
  }
}

</style>
